import Phaser from 'phaser'
import { ErrorHandler } from '../utils/ErrorHandler.js';
import { PerformanceUtils } from '../utils/PerformanceUtils.js';

export class DebugScene extends Phaser.Scene {
  debugPanel!: Phaser.GameObjects.Container
  isVisible= false
  updateTimer!: Phaser.Time.TimerEvent

  constructor() {
    super('DebugScene')
  }

  create() {
    // 创建调试面板
    this.createDebugPanel()
    
    // 默认隐藏
    this.debugPanel.setVisible(false)
    
    // 定期更新调试信息
    this.updateTimer = this.time.addEvent({
      delay: 1000,
      callback: this.updateDebugInfo,
      callbackScope,
      loop: true
    })

    // 快捷键切换显示
    this.input.keyboard?.on('keydown-F12', () => {
      this.toggleDebugPanel()
    })

    // 从其他场景也能切换
    this.game.events.on('toggle-debug', () => {
      this.toggleDebugPanel()
    })
  }

  createDebugPanel() {
    this.debugPanel = this.add.container(20, 20)

    // 背景
    const bg = this.add.rectangle(0, 0, 400, 500, 0x000000, 0.8)
    bg.setOrigin(0, 0)
    bg.setStrokeStyle(2, 0x00FF00)

    // 标题
    const title = this.add.text(10, 10, '🔧 调试面板', {
      fontSize: '18px',
      color: '#00FF00',
      fontFamily: 'monospace'
    })

    // 性能信息
    const perfTitle = this.add.text(10, 50, '性能信息:', {
      fontSize: '14px',
      color: '#FFFF00',
      fontFamily: 'monospace'
    })

    const perfInfo = this.add.text(10, 75, '', {
      fontSize: '12px',
      color: '#FFFFFF',
      fontFamily: 'monospace'
    })

    // 错误信息
    const errorTitle = this.add.text(10, 200, '错误日志:', {
      fontSize: '14px',
      color: '#FF0000',
      fontFamily: 'monospace'
    })

    const errorInfo = this.add.text(10, 225, '', {
      fontSize: '12px',
      color: '#FFFFFF',
      fontFamily: 'monospace'
    })

    // 系统信息
    const systemTitle = this.add.text(10, 350, '系统信息:', {
      fontSize: '14px',
      color: '#00FFFF',
      fontFamily: 'monospace'
    })

    const systemInfo = this.add.text(10, 375, '', {
      fontSize: '12px',
      color: '#FFFFFF',
      fontFamily: 'monospace'
    })

    // 操作按钮
    const clearLogsBtn = this.add.text(10, 450, '[C] 清空日志', {
      fontSize: '12px',
      color: '#FFFF00',
      fontFamily: 'monospace'
    }).setInteractive({ useHandCursor: true })

    const exportLogsBtn = this.add.text(120, 450, '[E] 导出日志', {
      fontSize: '12px',
      color: '#FFFF00',
      fontFamily: 'monospace'
    }).setInteractive({ useHandCursor: true })

    const closeBtn = this.add.text(350, 10, '[F12] 关闭', {
      fontSize: '12px',
      color: '#FF0000',
      fontFamily: 'monospace'
    }).setInteractive({ useHandCursor: true })

    // 按钮事件
    clearLogsBtn.on('pointerdown', () => {
      ErrorHandler.clearLogs()
      this.updateDebugInfo()
    })

    exportLogsBtn.on('pointerdown', () => {
      this.exportLogs()
    })

    closeBtn.on('pointerdown', () => {
      this.toggleDebugPanel()
    })

    // 键盘快捷键
    this.input.keyboard?.on('keydown-C', () => {
      if (this.isVisible) {
        ErrorHandler.clearLogs()
        this.updateDebugInfo()
      }
    })

    this.input.keyboard?.on('keydown-E', () => {
      if (this.isVisible) {
        this.exportLogs()
      }
    })

    this.debugPanel.add([
      bg, title, perfTitle, perfInfo, errorTitle, errorInfo,
      systemTitle, systemInfo, clearLogsBtn, exportLogsBtn, closeBtn
    ])

    // 保存引用以便更新
    this.debugPanel.setData('perfInfo', perfInfo)
    this.debugPanel.setData('errorInfo', errorInfo)
    this.debugPanel.setData('systemInfo', systemInfo)
  }

  updateDebugInfo() {
    if (!this.isVisible) return

    const perfInfo = this.debugPanel.getData('perfInfo') as Phaser.GameObjects.Text
    const errorInfo = this.debugPanel.getData('errorInfo') as Phaser.GameObjects.Text
    const systemInfo = this.debugPanel.getData('systemInfo') as Phaser.GameObjects.Text

    // 更新性能信息
    const fps = PerformanceUtils.getFPS()
    const memory = PerformanceUtils.getMemoryUsage()
    const perfLevel = PerformanceUtils.getDevicePerformanceLevel()
    
    const perfText = `FPS: ${fps}
内存: ${memory ? `${memory.used}MB (${memory.percentage}%)` : '不可用'}
设备性能: ${perfLevel}
活跃场景: ${this.scene.manager.getScenes(true).map(s => s.scene.key).join(', ')}`

    perfInfo.setText(perfText)

    // 更新错误信息
    const errors = ErrorHandler.getLogsByLevel('ERROR').slice(-5)
    const warnings = ErrorHandler.getLogsByLevel('WARNING').slice(-3)
    
    const errorText = `最近错误 (${errors.length}):
${errors.map(e => `${e.timestamp.toLocaleTimeString()}: ${e.message}`).join('\n')}

最近警告 (${warnings.length}):
${warnings.map(w => `${w.timestamp.toLocaleTimeString()}: ${w.message}`).join('\n')}`

    errorInfo.setText(errorText)

    // 更新系统信息
    const systemText = `分辨率: ${window.innerWidth}x${window.innerHeight}
缩放: ${window.devicePixelRatio}
在线: ${navigator.onLine ? '是' : '否'}
语言: ${navigator.language}
平台: ${navigator.platform}`

    systemInfo.setText(systemText)
  }

  toggleDebugPanel() {
    this.isVisible = !this.isVisible
    this.debugPanel.setVisible(this.isVisible)
    
    if (this.isVisible) {
      this.updateDebugInfo()
      ErrorHandler.logInfo('Debug panel opened')
    } else {
      ErrorHandler.logInfo('Debug panel closed')
    }
  }

  exportLogs() {
    try {
      const logs = ErrorHandler.exportLogs()
      const blob = new Blob([logs], { type: 'text/plain' })
      const url = URL.createObjectURL(blob)
      
      const a = document.createElement('a')
      a.href = url
      a.download = `stardigits-logs-${new Date().toISOString().slice(0, 19)}.txt`
      document.body.appendChild(a)
      a.click()
      document.body.removeChild(a)
      
      URL.revokeObjectURL(url)
      ErrorHandler.logInfo('Logs exported successfully')
    } catch (error) {
      ErrorHandler.logError('Failed to export logs', error)
    }
  }

  destroy() {
    if (this.updateTimer) {
      this.updateTimer.destroy()
    }
    this.game.events.off('toggle-debug')
    super.destroy()
  }
}
